package search.fibonacci;

import java.util.Arrays;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-06-04 13:25
 * @ Description :
 */
public class FibonacciSearch
{
    private static final int maxSize = 20;

    public static void main(String[] args)
    {
        int[] array = {1, 8, 10, 89, 1000, 1000, 1024};
        System.out.println(fibonacciSearch(array,89));
    }

    public static int[] fibonacci(int n)
    {
        int[] f = new int[n];
        if (n <= 2)
        {
            for (int i = 0; i < n; i++)
            {
                f[i] = 1;
            }
        }
        else
        {
            f[0] = 1;
            f[1] = 1;
            for (int i = 2; i < n; i++)
            {
                f[i] = f[i - 1] + f[i - 2];
            }
        }
        return f;
    }

    public static int fibonacciSearch(int[] array, int key)
    {
        int low = 0;
        int high = array.length - 1;
        int k = 0;//表示斐波那契分割数值的下标
        int mid = 0;

        int[] f = fibonacci(maxSize);
        while (high > f[k] - 1)
        {
            k++;
        }
        int[] temp = Arrays.copyOf(array,f[k]);
        for (int i = high + 1; i < temp.length ; i++)
        {
            temp[i] = array[high];
        }

        //下面开始查找
        while (low <= high)
        {
            mid = low + f[k - 1] - 1;
            if (key < temp[mid])
            {
                high = mid - 1;
                k--;
            }
            else if (key > temp[mid])
            {
                low = mid + 1;
                k -= 2;
            }
            else
            {
                return Math.min(mid, high);
            }
        }
        return -1;
    }
}
